import { defineStore } from 'pinia'
import { ref } from 'vue'
import axios from 'axios'

export interface Widget {
  id: number
  name: string
  version: string
  description: string
  author_id: number
  author_name?: string
  category: string
  is_active: boolean
  config_schema: string
  api_endpoints: string
  frontend_files: string
  created_at: string
  updated_at: string
}

export interface UserWidget {
  id: number
  user_id: number
  widget_id: number
  widget?: Widget
  is_enabled: boolean
  config_data: string
  created_at: string
  updated_at: string
}

export interface WidgetConfig {
  [key: string]: any
}

export const useWidgetStore = defineStore('widget', () => {
  const widgets = ref<Widget[]>([])
  const userWidgets = ref<UserWidget[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const loadedWidgets = ref<Record<string, any>>({})

  // 获取所有可用组件
  async function fetchWidgets(params?: { page?: number; pageSize?: number; search?: string; category?: string }) {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.get('/api/widgets/', { params })
      widgets.value = response.data.widgets || []
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取组件列表失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 获取用户的组件
  async function fetchUserWidgets() {
    loading.value = true
    error.value = null
    
    try {
      const response = await axios.get('/api/widgets/my/widgets')
      userWidgets.value = response.data || []
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取用户组件失败'
      throw err
    } finally {
      loading.value = false
    }
  }

  // 添加用户组件
  async function addUserWidget(widgetId: number, config: WidgetConfig = {}) {
    try {
      const response = await axios.post('/api/widgets/my/widgets', {
        widget_id: widgetId,
        config_data: JSON.stringify(config)
      })
      
      // 更新本地状态
      await fetchUserWidgets()
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '添加组件失败'
      throw err
    }
  }

  // 更新用户组件配置
  async function updateUserWidget(userWidgetId: number, config: WidgetConfig) {
    try {
      const response = await axios.put(`/api/widgets/my/widgets/${userWidgetId}`, null, {
        params: { config_data: JSON.stringify(config) }
      })
      
      // 更新本地状态
      const index = userWidgets.value.findIndex(w => w.id === userWidgetId)
      if (index !== -1) {
        userWidgets.value[index].config_data = JSON.stringify(config)
      }
      
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '更新组件配置失败'
      throw err
    }
  }

  // 删除用户组件
  async function deleteUserWidget(userWidgetId: number) {
    try {
      await axios.delete(`/api/widgets/my/widgets/${userWidgetId}`)
      
      // 更新本地状态
      userWidgets.value = userWidgets.value.filter(w => w.id !== userWidgetId)
    } catch (err: any) {
      error.value = err.response?.data?.detail || '删除组件失败'
      throw err
    }
  }

  // 启用/禁用用户组件
  async function toggleUserWidget(userWidgetId: number) {
    const userWidget = userWidgets.value.find(w => w.id === userWidgetId)
    if (!userWidget) return
    
    const newEnabledState = !userWidget.is_enabled
    const config = JSON.parse(userWidget.config_data || '{}')
    config.enabled = newEnabledState
    
    await updateUserWidget(userWidgetId, config)
  }

  // 获取组件分类列表
  async function fetchWidgetCategories() {
    try {
      const response = await axios.get('/api/widgets/categories/list')
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取组件分类失败'
      throw err
    }
  }

  // 获取已加载的组件信息
  async function fetchLoadedWidgets() {
    try {
      const response = await axios.get('/api/widgets/loaded')
      loadedWidgets.value = response.data
      return response.data
    } catch (err: any) {
      error.value = err.response?.data?.detail || '获取已加载组件失败'
      throw err
    }
  }

  // 解析组件配置
  function parseWidgetConfig(configData: string): WidgetConfig {
    try {
      return JSON.parse(configData || '{}')
    } catch {
      return {}
    }
  }

  // 获取已启用的用户组件
  function getEnabledUserWidgets(): UserWidget[] {
    return userWidgets.value.filter(w => w.is_enabled)
  }

  // 获取组件配置
  function getWidgetConfig(userWidgetId: number): WidgetConfig {
    const userWidget = userWidgets.value.find(w => w.id === userWidgetId)
    return userWidget ? parseWidgetConfig(userWidget.config_data) : {}
  }

  // 检查用户是否已有某个组件
  function hasUserWidget(widgetId: number): boolean {
    return userWidgets.value.some(w => w.widget_id === widgetId)
  }

  // 获取用户组件ID
  function getUserWidgetId(widgetId: number): number | null {
    const userWidget = userWidgets.value.find(w => w.widget_id === widgetId)
    return userWidget ? userWidget.id : null
  }

  return {
    widgets,
    userWidgets,
    loading,
    error,
    loadedWidgets,
    fetchWidgets,
    fetchUserWidgets,
    addUserWidget,
    updateUserWidget,
    deleteUserWidget,
    toggleUserWidget,
    fetchWidgetCategories,
    fetchLoadedWidgets,
    parseWidgetConfig,
    getEnabledUserWidgets,
    getWidgetConfig,
    hasUserWidget,
    getUserWidgetId
  }
})